/**
 * Created by zhaomi on 16/4/26.
 */
var mysql=require('mysql')
var connections=require('./conections')
var pool=mysql.createPool(connections)
// conn.connect(function(err){
//     if(err){
//         console.log('connection error')
//         return
//     }
//     console.log('connection success')
// })

module.exports.release=function(connections){
    connections.end(function(err){
        console.log('connection close')
    })
}
module.exports.execQuery=function(options){
    pool.getConnection(function(err,connection){
        if(err){
            console.log('database connection error')
            throw err
        }
        var sql=options.sql
        var params=options.params
        var handle=options.handle
        if(!params){
            connection.query(sql,function(err,results){
                if(err){
                    console.log('database connection error')
                    throw err
                }
                handle(results)
            })
        }else{
            connection.query(sql,params,function(err,results){
                if(err){
                    console.log('database connection error')
                    try{
                        throw err
                    }catch(e) {
                        console.log("error: "+e.stack)
                    }

                }
                handle(results)
            })
        }
        connection.release(function(err){
            if(err){
                console.log('database close error')
                try {
                    throw err
                }catch (e){
                    console.log("error: "+e.stack)
                }
            }
        })
    })
}
